<template>
  <el-dialog
    v-model="dialog.visible"
    :title="dialog.title ? dialog.title : '请正对摄像头'"
    :show-close="false"
    :close-on-click-modal="false"
    append-to-body
    center
    @open="openHandler"
    @close="closeHandler"
  >
    <el-image
      v-show="image"
      :src="image"
      style="width: 640px; height: 480px; margin: 0 auto; display: block"
    />
    <j-face-camera ref="faceCamera" v-show="!image" />

    <template v-if="showButton" #footer>
      <el-button
        @click="
          () => {
            dialog.visible = false
            $emit('cancel')
          }
        "
        >取消</el-button
      >
      <el-button v-if="!image" type="primary" @click="takePhotoHandler"
        >拍照</el-button
      >

      <template v-else>
        <el-button type="success" @click="image = ''">重拍</el-button>
        <el-button type="primary" @click="confirmHandler">确认</el-button>
      </template>
    </template>
  </el-dialog>
</template>
<script>
import JFaceCamera from './index'
import { compressImg } from '@/utils/compress'

export default {
  emits: ['success', 'cancel'],
  props: {
    dialog: {
      type: Object,
      required: true,
    },
    showButton: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      image: '',
    }
  },
  components: {
    JFaceCamera,
  },
  methods: {
    openHandler() {
      this.$nextTick(() => {
        this.tracking()
      })
    },
    closeHandler() {
      this.stop()
    },
    tracking() {
      this.$refs.faceCamera.tracking()
    },
    stop() {
      this.image = ''
      this.$refs.faceCamera.stop()
    },
    takePhotoHandler() {
      const value = this.$refs.faceCamera.capture()
      if (!value) {
        this.$message.warning('没有检测到人脸')
        return
      }

      compressImg(value).then((res) => {
        this.image = res
      })
    },
    confirmHandler() {
      this.dialog.value = this.image
      this.dialog.visible = false

      this.$emit('success', this.image)
    },
  },
}
</script>
<style lang="scss">
.faceCameraDialog {
  width: 680px;
  height: 660px;
}
</style>
